package com.songcha.module_home.ui.adapter

import android.app.Activity
import android.view.View
import android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.songcha.library_business.bean.advert.AdvertInfoBean
import com.songcha.library_business.bean.banner.BannerBean
import com.songcha.library_business.bean.book.BookBean
import com.songcha.library_business.bean.book.BookListBean
import com.songcha.library_business.bean.book.BookNetBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.handler.BookUriHandler
import com.songcha.library_business.helper.AdvertCoverHelper
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.interfaces.IOnBookClickListener
import com.songcha.library_business.ui.adapter.BookListAdapter
import com.songcha.library_business.ui.adapter.BookListAdapter2
import com.songcha.library_business.ui.adapter.SimpleBannerAdapter
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_business.util.MajiaBaoUtil
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.CustomButton
import com.songcha.library_common.ui.view.CustomContainerLayout
import com.songcha.library_common.ui.view.SmallDecimalView
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.JumpUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.module_home.R
import com.songcha.module_home.ui.activity.more_new_book.MoreNewBookShelveActivity
import com.songcha.module_home.ui.decoration.HomeHomeEditorRecommendItemDecoration
import com.songcha.module_home.ui.decoration.HomeHomeNewBookShelveItemDecoration
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseBannerAdapter
import com.zhpan.bannerview.constants.PageStyle
import com.zhpan.indicator.enums.IndicatorStyle


class HomeHomeAdapter(val activity: Activity,val frag: Fragment, list:MutableList<HomeMultiItemType>,val mBookClickListener:IOnBookClickListener,val mEditorRecommendRefreshListener:IOnEditorRecommendRefreshListener):BaseMultiItemQuickAdapter<HomeMultiItemType,BaseViewHolder>(list) {
    private var mMajiaName = "douyue"
    private var mHadLoadBannerAdvert = false

    interface IOnEditorRecommendRefreshListener{
        fun onRecommendRefresh()
    }

    init {
        mMajiaName = MajiaBaoUtil.getMajiaName()
        addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_TOP_BANNER,R.layout.home_home_multiitem_top_banner)
        //addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_ADVERT_XXL,R.layout.home_home_multiitem_advert_xxl)
        addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_EDITOR_RECOMMEND,R.layout.home_home_multiitem_editor_recommend)
        addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_MIDDLE_BANNER,R.layout.home_home_multiitem_middle_banner)
        if(mMajiaName=="douyue"){
            addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_NEWBOOK_SHELVE,R.layout.home_home_multiitem_newbook_shelve)
        }else if(mMajiaName=="beike"){
            addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_NEWBOOK_SHELVE,R.layout.home_home_multiitem_newbook_shelve)
        }

        addItemType(HomeMultiItemType.HOME_MULTIITEMTYPE_HOT_LSIT,R.layout.home_home_multiitem_host_list)
    }

    fun notifyBookHostListItem(start:Int,count:Int){
        if(itemCount == 0) return
        val vh=recyclerView.findViewHolderForAdapterPosition(itemCount-1)?:return
        vh as BaseViewHolder
        vh.getView<RecyclerView>(R.id.home_home_rcv_host_list).adapter?.notifyItemRangeChanged(start,count)
    }

    @Composable
    private fun TopBannerStackView(size:Int){
        if(size < 2) return
        Box(
            modifier = Modifier.fillMaxSize()
        ){
            if(size >= 3){
                Box(
                    modifier = Modifier.padding(16.dp,29.dp,16.dp)
                        .fillMaxSize()
                        .height(140.dp)
                        .clip(RoundedCornerShape(10.dp))
                        .background(Color(0xffE4E4FF))
                )
            }

            Box(
                modifier = Modifier.padding(9.dp,15.dp,9.dp)
                    .fillMaxSize()
                    .height(146.dp)
                    .clip(RoundedCornerShape(10.dp))
                    .background(Color(0xffD1D1FF))
            )

        }
    }

    override fun convert(holder:BaseViewHolder, item: HomeMultiItemType) {
        when(item.itemType){
            HomeMultiItemType.HOME_MULTIITEMTYPE_TOP_BANNER->{
                val bvp = holder.getView<BannerViewPager<Any>>(R.id.home_home_item_bvp)
                val cpvIndicator = holder.getView<ComposeView>(R.id.home_home_item_cpv)

                val bannerList = (item.data as BannerBean).data

                cpvIndicator.setContent {
                    TopBannerStackView(bannerList.size)
                }

                bvp.apply {
                    adapter = SimpleBannerAdapter() as BaseBannerAdapter<Any>
                    setPageStyle(PageStyle.MULTI_PAGE_OVERLAP)
                    //setRevealWidth(20.dp2px())
                    setIndicatorStyle(IndicatorStyle.ROUND_RECT)
                    //setIndicatorVisibility(View.GONE)
                    setIndicatorSliderColor(
                        ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_normal),
                        ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_selected))
                    registerLifecycleObserver(frag.lifecycle)

                    setOnPageClickListener{v,p->
                        BookUriHandler.handle(bannerList[p].tarUrl)
                    }

                    /*registerOnPageChangeCallback(object: OnPageChangeCallback(){
                        override fun onPageSelected(position: Int) {

                        }
                    })*/


                }.create(bannerList.toList())
                //bvp.refreshData(bannerList)
                bvp.descendantFocusability = FOCUS_BLOCK_DESCENDANTS
            }

            /*HomeMultiItemType.HOME_MULTIITEMTYPE_ADVERT_XXL->{
                val flAdvert = holder.getView<FrameLayout>(R.id.home_fl_advert_xxl)
                val cclAdvert = holder.getView<CustomContainerLayout>(R.id.home_ccl_advert_xxl)
                if(flAdvert.childCount > 0 || mHadLoadXxlAdvert) return

                mHadLoadXxlAdvert = true

                AdvertCoverHelper.loadAdvertByCover(activity,AdvertHelper.ADVERT_TYPE_XXL,VarConfig.ADVERT_HOME_XXL_INFO,
                    flAdvert,20f,object:AdvertHelper.ILoadAdvertCommonListener{
                        override fun onSuccess(type: Int, height: Int, view: View?) {
                            ViewHelper.setVisibility(true,flAdvert)
                            ViewHelper.setVisibility(true,cclAdvert)
                            flAdvert.removeAllViews()
                            flAdvert.addView(view)
                        }

                        override fun onError(type: Int,code:Int,msg:String) {
                            ViewHelper.setVisibility(false,flAdvert)
                            ViewHelper.setVisibility(false,cclAdvert)
                            flAdvert.removeAllViews()
                        }

                        override fun onClose(type: Int) {
                            ViewHelper.setVisibility(false,flAdvert)
                            ViewHelper.setVisibility(false,cclAdvert)
                            flAdvert.removeAllViews()
                        }

                    })

            }*/

            HomeMultiItemType.HOME_MULTIITEMTYPE_EDITOR_RECOMMEND->{
                val tvTitle = holder.getView<TextView>(R.id.home_tv_recommend_title)
                if(FunctionConfig.IS_PERSONAL_RECOMMEND_ENABLED){
                    tvTitle.text = "小编推荐"
                }else{
                    tvTitle.text = "大家在看"
                }
                val rcv=holder.getView<RecyclerView>(R.id.home_home_rcv_editor_recommend)
                val llRefresh=holder.getView<LinearLayout>(R.id.home_ll_editor_recommend_refresh)
                llRefresh.setOnClickListener {
                    mEditorRecommendRefreshListener.onRecommendRefresh()
                }

                rcv.apply {
                    val bookList=(item.data as BookListBean).data.records

                    layoutManager=GridLayoutManager(frag.requireContext(),3)
                    val adt=HomeHomeEditorRecommendAdapter(bookList,mBookClickListener)
                    adapter=adt
                    if(itemDecorationCount==0)
                        addItemDecoration(HomeHomeEditorRecommendItemDecoration())
                }
            }

            HomeMultiItemType.HOME_MULTIITEMTYPE_MIDDLE_BANNER->{
                val bvp=holder.getView<BannerViewPager<Any>>(R.id.home_home_item_bvp)
                val bannerList= (item.data as BannerBean).data

                bvp.apply {
                    adapter = SimpleBannerAdapter() as BaseBannerAdapter<Any>
                    setPageStyle(PageStyle.NORMAL)
                    //setRevealWidth(20.dp2px())
                    setIndicatorSliderColor(
                        ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_normal),
                        ColorUtil.getResourceColor(context, com.songcha.library_common.R.color.banner_indictor_selected))
                    registerLifecycleObserver(frag.lifecycle)

                    setOnPageClickListener{v,p->
                        BookUriHandler.handle(bannerList[p].tarUrl)
                    }
                }.create(bannerList.toList())
                //small screen device may cannot display
                //bvp.refreshData(bannerList)
                bvp.descendantFocusability=FOCUS_BLOCK_DESCENDANTS
            }

            HomeMultiItemType.HOME_MULTIITEMTYPE_NEWBOOK_SHELVE->{
                val bookList=(item.data as BookListBean).data.records
                var newBookShelveList = mutableListOf<BookNetBean>()

                val llMoreNewBook=holder.getView<LinearLayout>(R.id.home_ll_more_newbook)
                llMoreNewBook.setOnClickListener {
                    JumpUtil.toActivity(it.context,MoreNewBookShelveActivity::class.java)
                }

                //if(mMajiaName == "douyue"){
                    //render first book
                    val book=bookList[0]
                    val ivThumb=holder.getView<ImageView>(com.songcha.library_business.R.id.business_item_iv_thumb)
                    val tvBookName=holder.getView<TextView>(com.songcha.library_business.R.id.business_item_tv_book_name)
                    val tvDesc=holder.getView<TextView>(com.songcha.library_business.R.id.business_item_tv_desc)
                    val tvAuthor=holder.getView<TextView>(com.songcha.library_business.R.id.business_item_tv_author)
                    val tvScore=holder.getView<TextView>(com.songcha.library_business.R.id.business_item_tv_score)
                    val btnStartRead=holder.getView<CustomButton>(com.songcha.library_business.R.id.business_btn_start_read)

                    //TODO
                    GlideUtil.loadNetImage(ivThumb,book.cover)
                    tvBookName.text = book.bookName
                    tvDesc.text=book.description
                    tvAuthor.text=book.author
                    tvScore.text = StringUtil.float2PlainString(book.averageRating) + "分"

                    ivThumb.setOnClickListener {
                        //BusinessJumpUtil.toBookDetail(book.bookId.toString())
                        mBookClickListener.onBookClick(book.bookId.toString(),ivThumb)
                    }

                    btnStartRead.setOnClickListener {
                        val bean=BookBean().apply {
                            id=book.bookId.toString()
                            bookName=book.bookName
                            author=book.author
                            textCount=book.words
                            thumb=book.cover
                        }
                        BusinessJumpUtil.toBookReader(bean)
                    }


                    //newBookShelveList = bookList.subList(1,bookList.size)
                //}else if(mMajiaName == "beike"){
                    //newBookShelveList = bookList
                //}

                newBookShelveList = bookList.subList(1,bookList.size)

                val rcv = holder.getView<RecyclerView>(R.id.home_home_newbook_shelve_rcv)
                rcv.apply {
                    //layoutManager = GridLayoutManager(frag.requireContext(),2)
                    layoutManager = LinearLayoutManager(frag.requireContext(),LinearLayoutManager.HORIZONTAL,false)
                    val adt = HomeHomeNewBookShelveAdapter(newBookShelveList,mBookClickListener)
                    adapter = adt
                    if(itemDecorationCount == 0)
                        addItemDecoration(HomeHomeNewBookShelveItemDecoration())
                }

            }

            HomeMultiItemType.HOME_MULTIITEMTYPE_HOT_LSIT->{
                val rcv=holder.getView<RecyclerView>(R.id.home_home_rcv_host_list)
                //val flAdvert = holder.getView<FrameLayout>(R.id.home_fl_advert_banner)
                val bookList=(item.data as BookListBean).data.records

                rcv.apply {
                    layoutManager = LinearLayoutManager(frag.requireContext())
                    val adt = BookListAdapter2(bookList,mBookClickListener)
                    adapter = adt
                }

                /* if(mHadLoadBannerAdvert || flAdvert.childCount > 0)

                 mHadLoadBannerAdvert = true

                 AdvertCoverHelper.loadAdvertByCover(activity,AdvertHelper.ADVERT_TYPE_BANNER,VarConfig.ADVERT_HOME_BANNER_INFO,
                     flAdvert,140f,object :AdvertHelper.ILoadAdvertCommonListener{
                         override fun onSuccess(type: Int, height: Int, view: View?) {
                             ViewHelper.setVisibility(true,flAdvert)
                             if(type == AdvertInfoBean.ADVERT_TYPE_CSJ){
                                 //ViewHelper.setVisibility(true,cclAdvert)
                                 flAdvert.removeAllViews()
                                 flAdvert.addView(view)
                             }else{

                             }
                         }

                         override fun onError(type: Int,code:Int,msg:String) {
                             ViewHelper.setVisibility(false,flAdvert)
                             //ViewHelper.setVisibility(false,cclAdvert)
                             flAdvert.removeAllViews()
                         }

                         override fun onClose(type: Int) {
                             ViewHelper.setVisibility(false,flAdvert)
                             //ViewHelper.setVisibility(false,cclAdvert)
                             flAdvert.removeAllViews()
                         }

                     })*/

            }
        }
    }
}